package com.mmp.main.servlet.device;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mmp.common.bo.Message;
import com.mmp.common.servlet.BasicServlet;
import com.mmp.common.util.Common;
import com.mmp.main.DB.DBQueryManager;
import com.mmp.main.entity.Hospital;
import com.mmp.main.entity.HospitalDepatment;
import com.mmp.main.entity.HospitalDevice;
import com.mmp.main.entity.HospitalDeviceAccessory;
import com.mmp.main.entity.LookupDeviceCategory;
import com.mmp.main.util.Default;
import com.mmp.main.util.Enums;
import com.mmp.main.util.WebUtil;

public class DeviceInfoProcessServlet extends BasicServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String deviceId = request.getParameter("deviceId");

		HospitalDevice device = new DBQueryManager(dbm).checkDeviceCodeOrSerialDuplication(
				request.getParameter("code"), request.getParameter("serial"),
				(deviceId != null && !deviceId.isEmpty()) ? Integer.parseInt(deviceId) : 0);

		if (device != null) {
			announceErorrMessage(request, response,
					"لم تتم العملية بنجاح .. يوجد بالفعل جهاز بنفس الكود أو الرقم التسلسلي .. كود الجهاز الموجود هو  "
							+ device.getCode() + " ورقمه التسلسلي هو " + device.getSerialNo());
			return;
		}

		if (deviceId != null && !deviceId.isEmpty()) { // update mode
			device = dbm.findById(Integer.parseInt(deviceId), HospitalDevice.class);

		} else { // entry mode

			/*
			 * // check if another device registered with the submitted code if
			 * (new DBQueryManager(dbm).getDevice(request.getParameter("code"),
			 * null, null, false) != null) { setMessage(request, new Message(
			 * "لم تتم العملية بنجاح .. يوجد بالفعل جهاز بنفس الكود الذي تم إدخاله"
			 * , Message.MESSAGE_TYPE.ERROR)); sendRedirect(request, response,
			 * "DeviceInfoDisplay"); return; }
			 * 
			 * // check if another device registered with the submitted serial
			 * // number if (new DBQueryManager(dbm).getDevice(null,
			 * request.getParameter("serial"), null, false) != null) {
			 * setMessage(request, new Message(
			 * "لم تتم العملية بنجاح .. يوجد بالفعل جهاز بنفس الرقم التسلسلي الذي تم إدخاله"
			 * , Message.MESSAGE_TYPE.ERROR)); sendRedirect(request, response,
			 * "DeviceInfoDisplay"); return; }
			 */
			device = new HospitalDevice();
			device.setStatus(Enums.DEVICE_STATUS.WORK_PROPERLY.getStatus());

			Hospital hospital = new Hospital();
			hospital.setId(getSessionUser(request).getHospital().getId());
			device.setHospital(hospital);
		}

		device.setCode(WebUtil.getParamValue(request, "code", null));
		device.setSerialNo(WebUtil.getParamValue(request, "serial", null));
		device.setDeviceName(WebUtil.getParamValue(request, "name", null));
		device.setManufacturerName(WebUtil.getParamValue(request, "manufacturerName", null));
		device.setModel(WebUtil.getParamValue(request, "model", null));

		int category = WebUtil.getParamValueAsInteger(request, "category", 0);
		if (category != 0) {
			LookupDeviceCategory categoryObj = new LookupDeviceCategory();
			categoryObj.setId(category);
			device.setLookupDeviceCategory(categoryObj);
		}

		device.setAgentName(WebUtil.getParamValue(request, "agentName", null));

		device.setSubcontractor(WebUtil.getParamValue(request, "subcontractor", null));

		int dep = WebUtil.getParamValueAsInteger(request, "dep", 0);
		if (dep != 0) {
			HospitalDepatment depObj = new HospitalDepatment();
			depObj.setId(dep);
			device.setHospitalDepatment(depObj);
		}

		device.setOperationDate(WebUtil.getParamValueAsDate(request, "operationDate", null));
		device.setTa3midNo(WebUtil.getParamValue(request, "ta3midNo", null));
		device.setPrice(WebUtil.getParamValueAsFloat(request, "price", 0));

		String withinWarranty = request.getParameter("withinWarranty");
		if (withinWarranty != null)
			device.setWithinWarranty("1".equals(withinWarranty) ? true : false);

		if (device.getWithinWarranty() != null && device.getWithinWarranty() == true) {
			device.setWarrantyExpireDate(WebUtil.getParamValueAsDate(request, "warrantyExpireDate", null));
		} else {
			String withinContract = request.getParameter("withinContract");
			if (withinContract != null)
				device.setWithinContract("1".equals(withinContract) ? true : false);

			if (device.getWithinContract() != null && device.getWithinContract() == false) {

				String addedFromAnotherLocation = request.getParameter("addedFromAnotherLocation");
				if (addedFromAnotherLocation != null)
					device.setAddedFromAnotherLocation("1".equals(addedFromAnotherLocation) ? true : false);

				if (device.getAddedFromAnotherLocation() != null && device.getAddedFromAnotherLocation() == true) {
					device.setLocationName(WebUtil.getParamValue(request, "locationName", null));
					device.setAddDate(WebUtil.getParamValueAsDate(request, "addDate", null));

				}
			}
		}

		device.setPmAnnualVisitsNo(WebUtil.getParamValueAsInteger(request, "pmAnnualVisitsNo", 0));

		String[] pmVisitsMonths = request.getParameterValues("pmVisitsMonths");
		if (pmVisitsMonths != null && pmVisitsMonths.length != 0)
			device.setPmVisitsMonths(Common.concatenateValues(pmVisitsMonths));

		if (device.getHospitalDeviceAccessories() == null)
			device.setHospitalDeviceAccessories(new ArrayList<HospitalDeviceAccessory>());
		else
			device.getHospitalDeviceAccessories().clear();

		String deviceAccessories_rowOrder = request.getParameter("deviceAccessories_rowOrder");
		if (deviceAccessories_rowOrder != null && !deviceAccessories_rowOrder.isEmpty()) {

			String[] indexes = deviceAccessories_rowOrder.split(",");
			for (int i = 0; i < indexes.length; i++) {
				HospitalDeviceAccessory acc = new HospitalDeviceAccessory();
				acc.setQuantity(WebUtil.getParamValueAsInteger(request, "deviceAccessories_accQuantity_" + indexes[i],
						0));
				acc.setDescription(WebUtil.getParamValue(request, "deviceAccessories_accDescription_" + indexes[i],
						null));
				device.addHospitalDeviceAccessory(acc);
			}
		}

		device = dbm.mergeEntity(device);

		if (deviceId == null) {
			setMessage(request, new Message("تمت  إضافة الجهاز بنجاح", Message.MESSAGE_TYPE.SUCCESS));
			sendRedirect(request, response, "DeviceInfoDisplay");

		} else {
			setMessage(request, new Message("تم تعديل بيانات الجهاز بنجاح", Message.MESSAGE_TYPE.SUCCESS));

			sendRedirect(
					request,
					response,
					"SearchForDeviceDisplay?" + Default.SEARCH_DEST_PARAM_NAME + "="
							+ Default.SEARCH_DEST_UPDATE_DEVICE_PARAM_VALUE);
		}
	}
}
